import { Table, TableProps } from 'antd';
import { useState } from 'react';

interface DataTableProps<T> extends Omit<TableProps<T>, 'pagination'> {
  fetchData?: (params: any) => Promise<{ items: T[]; total: number }>;
  pageSize?: number;
}

export function DataTable<T extends object>({
  fetchData,
  pageSize = 10,
  ...props
}: DataTableProps<T>) {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<T[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize,
    total: 0,
  });

  const handleTableChange = async (newPagination: any) => {
    if (!fetchData) return;

    setLoading(true);
    try {
      const result = await fetchData({
        page: newPagination.current,
        limit: newPagination.pageSize,
      });
      setData(result.items);
      setPagination({
        ...newPagination,
        total: result.total,
      });
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Table
      {...props}
      dataSource={data}
      pagination={pagination}
      loading={loading}
      onChange={handleTableChange}
    />
  );
}